package com.wejoy.video.middle.station.data.util.excel;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 *
 * @author: admin
 * @time: 2022/9/16 11:20
 */
public final class EasyExcelUtils {

    private final static Logger logger = LoggerFactory.getLogger(EasyExcelUtils.class);


    /**
     * sheet编号
     */
    private static final int sheetNo = 1;
    /**
     * 从第几行开始读
     */
    private static final int headLineMun = 0;

    public static final List<List<String>> headList = new ArrayList<>();

    static {
        headList.add(Stream.of("列1").collect(Collectors.toList()));
    }

    /**
     * 根据模型关系构建excel文件
     */
    public static <T extends BaseRowModel> void accordingModelRelationBuilder(
            Class<? extends BaseRowModel> clazz, List<? extends BaseRowModel> tList, String url, ExcelTypeEnum typeEnum)
            throws FileNotFoundException {
        OutputStream outputStream = new FileOutputStream(url);
        try {
            ExcelWriter writer = new ExcelWriter(outputStream, typeEnum);
            Sheet sheet1 = new Sheet(sheetNo, headLineMun, clazz);
            sheet1.setAutoWidth(Boolean.TRUE);
            writer.write(tList, sheet1);
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 自定义excel文件
     */
    public static <T extends BaseRowModel> void customBuilder(
            Class<? extends BaseRowModel> clazz, List<List<Object>> tList, String url, ExcelTypeEnum typeEnum,
            String sheetName, List<List<String>> headList)
            throws FileNotFoundException {
        OutputStream outputStream = new FileOutputStream(url);
        try {
            ExcelWriter writer = new ExcelWriter(outputStream, typeEnum);
            Sheet sheet1 = new Sheet(sheetNo, headLineMun, clazz, sheetName, headList);
            sheet1.setAutoWidth(Boolean.TRUE);
            writer.write1(tList, sheet1);
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T extends BaseRowModel> List<T> readExcel(final InputStream inputStream, final Class<? extends BaseRowModel> clazz) {
        if (null == inputStream) {
            throw new NullPointerException("the inputStream is null!");
        }
        EasyExcelListener<T> listener = new EasyExcelListener<>();
        // 这里因为EasyExcel-1.1.1版本的bug，所以需要选用下面这个标记已经过期的版本
        ExcelReader reader = new ExcelReader(inputStream, valueOf(inputStream), null, listener);
        reader.read(new Sheet(1, 1, clazz));
        return listener.getRows();
    }

    public static void writeExcel(final File file, List<? extends BaseRowModel> list) {
        try (OutputStream out = new FileOutputStream(file)) {
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            //写第一个sheet,  有模型映射关系
            Class<? extends BaseRowModel> t = null;
            if (CollectionUtils.isNotEmpty(list)) {
                t = list.get(0).getClass();
            } else {
                t = BaseRowModel.class;
            }
            Sheet sheet = new Sheet(1, 0, t);
            writer.write(list, sheet);
            writer.finish();
        } catch (IOException e) {
            logger.warn("fail to write to excel file: file[{}]", file.getName(), e);
        }
    }


    /**
     * 根据输入流，判断为xls还是xlsx，该方法原本存在于easyexcel 1.1.0 的ExcelTypeEnum中。
     */
    public static ExcelTypeEnum valueOf(InputStream inputStream) {
        try {
            FileMagic fileMagic = FileMagic.valueOf(inputStream);
            if (FileMagic.OLE2.equals(fileMagic)) {
                return ExcelTypeEnum.XLS;
            }
            if (FileMagic.OOXML.equals(fileMagic)) {
                return ExcelTypeEnum.XLSX;
            }
            throw new IllegalArgumentException("excelTypeEnum can not null");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
